package db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.ErrorCode;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class MyJDBCAppender extends JDBCAppender {
	
private DruidDataSource dataSource;
	
	public MyJDBCAppender()
	{
		super();
	}
	
	@Override
	protected void closeConnection(Connection con)
	{
		try
		{
			/* 如果数据库连接对象不为空和没有被关闭的话，关闭数据库连接 */
			if ( con != null && !con.isClosed())
				con.close();
			
		} 
		catch (SQLException e)
		{
			errorHandler.error("Error closing MyJDBCAppender.closeConnection() 's connection",e,ErrorCode.GENERIC_FAILURE); 
		}
	}

	@Override
	protected Connection getConnection() throws SQLException
	{
		/* 获取数据库配置property */
		Properties properties = new Properties();
		try {
			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		String className = String.valueOf(properties.getProperty("driver",""));
		String connUrl = String.valueOf(properties.getProperty("url",""));
		String uname = String.valueOf(properties.getProperty("username",""));
		String psw = String.valueOf(properties.getProperty("password",""));
		String maxActive = String.valueOf(properties.getProperty("maxActive",""));
		String minIdle = String.valueOf(properties.getProperty("minIdle",""));

		Properties result = new Properties();
		result.put("driverClassName",className);
		result.put("url",connUrl);
		result.put("username",uname);
		result.put("password",psw);
		
		result.put("maxActive",maxActive);
		result.put("minIdle",minIdle);

		try
		{
			dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(result);
		}
		catch (Exception e)
		{
			/* Druid数据库源对象产生失败后，取消初始化 */
			try {uninitialize();} catch(Exception e2) {}
			throw new SQLException(e);
		}
		
		return dataSource.getConnection();
	}

	/* 取消初始化 */
	public void uninitialize()
	{
		try
		{
			if (dataSource != null)
				dataSource.close();
		} 
		catch (Exception e)
		{
			try {
				throw new SQLException(e);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		finally
		{
			super.close();
		}
	} 

}
